import configHttp from "./config-http";
import axios from "axios";

const http = {
  get: (url, params, config) => {
    return new Promise((resolve, reject) => {
      _request("GET", url, params, resolve, reject, config);
    });
  },
  post: (url, params, config) => {
    return new Promise((resolve, reject) => {
      _request("POST", url, params, resolve, reject, config);
    });
  }
};

function _request(method, url, params, resolve, reject, conf) {
  let config = conf || {};
  // 后端数据返回格式（用户可以根据各个产品的后端返回自行改变）
  // {
  //   "code": '200', // 200、正常。 -1、未登录或者登陆过期。 其他弹出toast
  //   "message": "some message",
  //   "data": *
  // }
  // let access_token = localStorage.getItem('access_token');
  // axios.defaults.headers['Authorization'] = access_token;
  axios({
    url: `${configHttp.baseURL}${url}`,
    method: method,
    headers: {
      'Authorization': localStorage.getItem('access_token')
    },
    data: Object.assign({}, params),
    ...config
  })
    .then(res => {
      _dealResponse(res, resolve, reject);
    })
    .catch(res => {
      _dealResponse(res, resolve, reject);
    });
}

/**
 * 处理数据返回
 * @param {*} res
 * @param {*} resolve
 * @param {*} reject
 */
function _dealResponse(res, resolve, reject) {
  // console.log("_dealResponse", res);
  const data = res.data || res;
  const code = data.code;
  // code状态码含义
  // 1：成功
  // -1：用户未登录
  // 其他： 其他

  // 后端会将错误文案放在msg里面
  switch (code) {
    case "200":
      resolve(data.data);
      break;
    case 401:
      reject({
        text: data.message,
        code
      });
      break;
    default:
      reject({
        text: data.message,
        code
      });
  }
}

export default http;
